package net.akkz.urlMapping;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.akkz.beanFactory.ActionFactoryWithPermission;
import net.akkz.model.Result;

public class UrlMappingWithPermissionProperty implements Filter
{
	ActionFactoryWithPermission actionFactory;
	
	@Override
	public void destroy()
	{
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filter) throws IOException, ServletException
	{
		try
		{
			HttpServletRequest req = (HttpServletRequest) request;
			HttpServletResponse res = (HttpServletResponse)response;
			
			String path = req.getServletPath();
			
			int servletIndex = path.lastIndexOf('/');
			int dollIndex = path.lastIndexOf('.');
			
			String servlet = null;
			String method = null;
			String url = null;
			
			if(dollIndex == -1)
			{
				servlet = path.substring(servletIndex+1);
				method = "";
				url = path;
			}
			else
			{
				servlet = path.substring(servletIndex+1, dollIndex);
				method = path.substring(dollIndex + 1);
				url = path.substring(0, dollIndex);
			}
			
			Result result = actionFactory.excute(servlet, method, req, res);
			
			if(result.getRedirectWay().equals("redirect"))
			{
				res.sendRedirect(result.getView());
			}
			else
			{
				req.getRequestDispatcher(result.getView()).forward(request, response);
			}
		}
		catch (StringIndexOutOfBoundsException e)
		{
			e.printStackTrace();
			
			throw new ServletException(e);
		}
	}

	@Override
	public void init(FilterConfig filter) throws ServletException
	{
		actionFactory = (ActionFactoryWithPermission) filter.getServletContext().getAttribute("actionFactory");
	}
}
